<?php

namespace App\Models\Common;

use App\Models\Member\Member;
use App\Models\Sys\User;
use App\Services\Com\LogService;
use Emadadly\LaravelUuid\Uuids;
use Illuminate\Support\Facades\Route;
use WeSoonNet\LaravelPlus\Traits\Timezone;
use Illuminate\Database\Eloquent\Model;

class Code extends Model
{
    use Uuids, Timezone;

    protected $table        = 'com_code';
    protected $guarded      = ['created_at', 'updated_at'];
    protected $hidden       = ['pivot'];
    protected $casts        = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'deleted_at' => 'datetime:Y-m-d H:i:s',
    ];

    public static function boot()
    {
        parent::boot();

        static::created(function ($model)
        {
            LogService::write('C', true, Route::currentRouteName(), json_encode($model->attributes), $model->table);
        });

        static::updated(function ($model)
        {
            // 对比更改
            $original = $model->getOriginal();
            $changes  = [];
            foreach ($model->getChanges() as $key => $value)
            {
                $changes[$key] = [
                    'old' => $original[$key],
                    'new' => $value,
                ];
            }
            LogService::write('U', true, Route::currentRouteName(), json_encode($changes), $model->table);
        });

        static::deleted(function ($model)
        {
            LogService::write('D', true, Route::currentRouteName(), json_encode($model->attributes), $model->table);
        });
    }

    public static $stateArr = [
        0 => '禁用',
        1 => '正常',
    ];

    /**
     * 用户
     */
    public function member()
    {
        return $this->belongsTo(Member::class, 'member_uuid', 'uuid');
    }

    /**
     * 后台管理员
     */
    public function sysUser()
    {
        return $this->belongsTo(User::class, 'member_uuid', 'id');
    }
}
